package com.example.controller;

import com.example.common.lang.Result;
import com.example.service.PostService;
import com.example.util.RedisUtil;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.ZSetOperations;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.ResponseBody;

import java.util.*;

@Controller
public class IndexController extends BaseController {

    @Autowired
    PostService postService;

    @Autowired
    RedisUtil redisUtil;

    @RequestMapping({"", "/", "/index"})
    public String index () {
        return "index";
    }

    @ResponseBody
    @RequestMapping({"getWeekRank"})
    public Result getWeekRank() {
        Set<ZSetOperations.TypedTuple> weekRank = redisUtil.getZSetRank("week_rank", 0, -1);

        List<Map> hostPosts = new ArrayList<>();

        for(ZSetOperations.TypedTuple typedTuple : weekRank) {

            Map map = new HashMap();

            map.put("id", redisUtil.hget("post_" + typedTuple.getValue(), "post:id"));
            map.put("title", redisUtil.hget("post_" + typedTuple.getValue(), "post:title"));
            map.put("commentCount", typedTuple.getScore());

            hostPosts.add(map);
        }

        return Result.succ(hostPosts);
    }

}
